package com.richie696.bank.account.service.impl;

import com.richie696.bank.account.dao.AccountDAO;
import com.richie696.bank.account.domian.Account;
import com.richie696.bank.account.model.AccountRequestModel;
import com.richie696.bank.account.model.AccountResponseModel;
import com.richie696.bank.account.service.AccountService;
import com.richie696.bank.json.ExecuteResult;
import spring.annotations.Autowired;
import spring.annotations.Service;
import spring.annotations.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDAO accountDAO;

    @Transactional
    @Override
    public ExecuteResult<AccountResponseModel> doTransferProcess(AccountRequestModel model) {
        if (Objects.isNull(model) || model.isInvalid()) {
            return ExecuteResult.getErrorResult("转账执行失败，请重试。");
        }
        Account fromAccount = accountDAO.selectOne(model.getFromCardNo());
        Account toAccount = accountDAO.selectOne(model.getToCardNo());
        BigDecimal transferMoney = model.getMoneyNumeric();
        ExecuteResult<AccountResponseModel> result = doTransferProcessBefore(fromAccount, toAccount, transferMoney);
        if (!result.isSuccess()) {
            return result;
        }
        int res = accountDAO.update(fromAccount);
        if (res != 1) {
            return result.setErrorMessage("转账失败。");
        }

        res = accountDAO.update(toAccount);
        if (res != 1) {
            return result.setErrorMessage("转账失败。");
        }
        return result.setData(new AccountResponseModel(fromAccount.getMoney().longValue(), toAccount.getMoney().longValue()));
    }

    private ExecuteResult<AccountResponseModel> doTransferProcessBefore(
            Account fromAccount, Account toAccount, BigDecimal transferMoney) {
        if (Objects.isNull(fromAccount)) {
            return ExecuteResult.getErrorResult("指定的转出方账户不存在。");
        }
        if (Objects.isNull(toAccount)) {
            return ExecuteResult.getErrorResult("指定的转入方账户不存在。");
        }
        if (transferMoney.compareTo(BigDecimal.ZERO) < 0) {
            return ExecuteResult.getErrorResult("转账金额有误，请重试。");
        }
        BigDecimal fromMoney = fromAccount.getMoney().subtract(transferMoney);
        if (fromMoney.compareTo(BigDecimal.ZERO) < 0) {
            return ExecuteResult.getErrorResult("指定的转出方账户余额不足。");
        }
        fromAccount.setMoney(fromMoney);
        toAccount.setMoney(toAccount.getMoney().add(transferMoney));
        return ExecuteResult.getSuccess();
    }

}
